import urllib.parse,requests,re,os;
import getopt,sys

real_url,file_name='',''
def parse():
    values = {};is_down = False
    try:
        options, args = getopt.getopt(sys.argv[1:], "d:n:")
    except getopt.GetoptError:
        sys.exit()
    for option, value in options:
        if option in ("-d"):
            is_down = True
            values['key'] = value
        if option in ("-n"):
            values['key'] = value
    if args:
        print("命令参数错误！")
        sys.exit(0)

    values['pn']='1'
    values['rn']='30'
    values['httpsStatus']='1'
    values['reqId']='cc337fa0-e856-11ea-8e2d-ab61b365fb50'
    param=urllib.parse.urlencode(values)
    url = 'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?'+param
    rids = [];name =[]
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36 Edg/84.0.522.63",
        "Cookie":"_ga=GA1.2.1083049585.1590317697; _gid=GA1.2.2053211683.1598526974; _gat=1; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1597491567,1598094297,1598096480,1598526974; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1598526974; kw_token=HYZQI4KPK3P",
        "Referer": "http://www.kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6",
        "csrf": "HYZQI4KPK3P"}
    try:
        global real_url;global file_name;
        r=requests.get(url,headers = headers)
        r.encoding = 'utf-8'
# -------------------------解析歌手名字，歌曲名字-----------------------------
        item = r.json()['data']['list']
        for index,i in enumerate(range(len(item))):
            actor = r.json()['data']['list'][i]['artist']
            music_name = r.json()['data']['list'][i]['name']
            print(index,actor,music_name)
            name.append(music_name)
            
# ------------------------提取关键参数-----------------------------------------------            
        for rid in re.findall('\d+(?=,"duration")',r.text):
            rids.append(rid)
        reqid = re.findall('(?<=","reqId":")(.*)(?="})',r.text)[0]

# ------------------------重新拼装url-------------------------------------------------
        string = input("请输入对应序号的歌曲:")
        num = int(string)
        link = 'https://www.kuwo.cn/url?format=mp3&rid={}&response=url&type=convert_url3&br=128kmp3&from=web&httpsStatus=1&reqId={}'.format(rids[num],reqid)
        res = requests.get(link)
        real_url = res.json()['url']
        file_name = name[num]
    except:
        print("请求失败，检查歌曲名称重试。")

    if is_down:
        download()
    else:
        online()

def online():
    try:
       os.system("mpv %s"%(real_url))
    except:
        print("请复制运行此条命令:'pkg install mpv'")
        


def download():
        down = requests.get(real_url)
        root = '/storage/emulated/0/%s.mp3'%(file_name)
        with open(root,'ab')as file:
            file.write(down.content)
            os.system('xdg-open "%s"'%(root))
  
def main():
    parse()




        
if __name__ =='__main__':
    main()